<template>
    <el-card>
        <el-card>
            <div>
                <div class="outer">
                    <el-radio-group v-model="currentPaper" @change="fetchData">
                        <el-radio-button label="A">A 卷</el-radio-button>
                        <el-radio-button label="B">B 卷</el-radio-button>
                    </el-radio-group>
                    <el-dialog v-model="dialogVisible_ForScore" :show-close="false" :close-on-click-modal="false"
                        title="设置单题分数" width="500" align-center>
                        <el-form :model="questionTypesForSingle" ref="formRef" label-width="100px">
                            <el-form-item label="单项选择题" prop="oneChoiceQuestions">
                                <el-input type="number"
                                    v-model.number="questionTypesForSingle.oneChoiceQuestions"></el-input>
                            </el-form-item>
                            <el-form-item label="多项选择题" prop="multipleChoiceQuestions">
                                <el-input type="number"
                                    v-model.number="questionTypesForSingle.multipleChoiceQuestions"></el-input>
                            </el-form-item>
                            <el-form-item label="填空题" prop="fillBlankQuestions">
                                <el-input type="number"
                                    v-model.number="questionTypesForSingle.fillBlankQuestions"></el-input>
                            </el-form-item>
                            <el-form-item label="判断题" prop="judgeQuestions">
                                <el-input type="number"
                                    v-model.number="questionTypesForSingle.judgeQuestions"></el-input>
                            </el-form-item>
                        </el-form>
                        <template #footer>
                            <div class="dialog-footer">
                                <el-button @click="dialogVisible_ForScore = false">取消</el-button>
                                <el-button type="primary" @click="modifyQuestionSingleScore">
                                    确认修改
                                </el-button>
                            </div>
                        </template>
                    </el-dialog>
                    <div class="btnGroup">
                        <el-button @click="openDialog">编辑试卷题型顺序</el-button>
                        <el-button @click="openDialogForScore">设置单题分数</el-button>
                    </div>
                    <EditPaperOrderDialog :editing="true" :questionTypes="questionTypes"
                        :currentPaperType="currentPaper" :dialogVisible="dialogVisible"
                        @update:dialogVisible="updateDialogVisible" @save="handleSave" />
                </div>
                <el-table :data="tableData" style="width: 100%" :span-method="spanMethod">
                    <el-table-column width="200" prop="target_name" label="课程目标">
                        <template #default="{ row }">
                            <span v-if="row.isFirstOfGroup">{{ row.target_name }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column width="200" prop="target_desc" label="考核内容">
                        <template #default="{ row }">
                            <div class="target_desc_class" v-if="row.isFirstOfGroup"
                                v-for="(content, index) in row.target_desc" :key="index">{{ content
                                }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="题目标签">
                        <template #default="{ row }">
                            <el-select v-model="row.label" multiple collapse-tags collapse-tags-tooltip
                                placeholder="请选择标签" style="width: 200px" @change="handleChangeLabel(row)">
                                <el-option v-for="item in options_for_label" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </template>
                    </el-table-column>

                    <el-table-column width="300" label="题型">
                        <template #default="{ row }">
                            <el-select v-model="row.questionType" placeholder="请选择">
                                <el-option v-for="option in options" :key="option.value" :label="option.label"
                                    :value="option.value" />
                            </el-select>
                            <el-button @click="addRow(row)" style="margin-left: 10px;" type="primary" size="small"
                                circle :icon="Plus" plain></el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label="题数">
                        <template #default="{ row }">
                            <el-input v-model.number="row.questionNum" type="number" min="1" />
                        </template>
                    </el-table-column>
                    <el-table-column label="分数">
                        <template #default="{ row }">
                            <!-- <el-input v-model.number="row.score" type="number" min="1" /> -->
                            <!-- <span>{{ row.score }}</span> -->
                            <span v-if="row.questionType === '单项选择题'">{{
                        row.questionNum * questionTypesForSingle.oneChoiceQuestions || 0 }}</span>
                            <span v-if="row.questionType === '多项选择题'">{{
                        row.questionNum * questionTypesForSingle.multipleChoiceQuestions || 0 }}</span>
                            <span v-if="row.questionType === '填空题'">{{
                        row.questionNum * questionTypesForSingle.fillBlankQuestions || 0 }}</span>
                            <span v-if="row.questionType === '判断题'">{{
                        row.questionNum * questionTypesForSingle.judgeQuestions || 0 }}</span>

                            <!-- <el-input v-model.number="row.score" type="number" min="1" /> -->

                        </template>
                    </el-table-column>
                    <el-table-column width="50">
                        <template #default="{ row }">
                            <el-button @click="deleteRow(row)" type="danger" circle :icon="Delete" plain></el-button>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <el-empty></el-empty>
                    </template>
                </el-table>

                <div class="upload-area">
                    <el-button type="primary" @click="uploadData">保存</el-button>
                    <el-tag size="large" type="primary">当前总分: {{ totalScore || 0 }}</el-tag>
                </div>
            </div>
        </el-card>
        <el-card>
            <button @click="makePaper" class="button">去组卷</button>
        </el-card>
    </el-card>
</template>
<script setup>
import { reactive, ref, onMounted, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { addLabelForTarget, delLabelForTarget, updateQuestionsSingleScore, getQuestionsSingleScore, getTotalTarget, updateTotalTarget, addSingleTargetInfo, delSingleTargetInfo, getQuestionType, getTargetScore, getLabelForSelection, getQuestionsTypeForSelection } from '@/api/target_item_info_input';
import EditPaperOrderDialog from './draggbleCompo.vue';
import { Delete, Plus } from '@element-plus/icons-vue';
import { useClassStore } from '@/stores/modules/class'
const classStore = useClassStore()
const acs_id = classStore.classInfo.user_and_acs_id
const options = ref([])
// 在表格数据加载时，保存一份原始数据的副本
let originalTableData = [];
const handleChangeLabel = async (row) => {
    // 每次传来的row.label都是只有文字的，没有和标签库的数据结构对应  所以下面的changedLabels和originalLabels都是只有文字的
    console.log("row.label", row.label);
    // 获取标签变化后的值
    const targetId = row.targetId
    let changedLabels = row.label;
    // 获取原始数据中该行的标签
    const originalRow = originalTableData.find(item => item.id === row.id);
    const originalLabels = originalRow ? originalRow.label : [];
    console.log("先", changedLabels, originalLabels);

    const deletedLabels = originalLabels.find(label => {
        // console.log("changedLabels.includes(label)", label,changedLabels.includes(label));
        return !changedLabels.includes(label)
    });

    const addLabel = changedLabels.find(label => label.id === undefined)
    console.log("addLabel", addLabel);
    console.log("deletedLabels", deletedLabels);
    if (addLabel != undefined) {
        const completeLabel = options_for_label.value.find(label => label.value === addLabel)
        console.log("targetId", targetId);
        console.log("completeLabel", completeLabel.id);
        // await addLabelForTarget(targetId, completeLabel.id)
        // tableData.splice(lastIndex + 1, 0, newRow); // 在该组的最后一行后面插入新行
        tableData.forEach((item) => {
            if (item.id === row.id) {
                item.label = item.label.map(item_1 => {
                    if (item_1.id === undefined) {
                        return completeLabel
                    } else {
                        return item_1
                    }
                })
            }
        });
        return
    }
    if (deletedLabels != undefined) {
        // await delLabelForTarget(targetId, deletedLabels.id)
        console.log("tableData", tableData);

    }
    originalTableData = JSON.parse(JSON.stringify(tableData));
};

const getQuestionsTypeForSelection_func = async (acs_id) => {
    // 下拉框中的题型赋值
    options.value = [];
    questionTypes.splice(0);
    try {
        await getQuestionsTypeForSelection(acs_id).then(res => {
            res.data.content.forEach((item, index) => {
                // console.log(item, index);
                options.value.push({ value: item.type, label: item.type })
                questionTypes.push({ id: index + 1, type: item.type, userInput: '', selected: false })
            })
        })
    } catch (error) {
        console.error('获取题型失败:', error);
    }
    try {
        //    获取标签赋值给下拉框
        await getLabelForSelection(subId).then(res => {
            res.data.content.forEach((item, index) => {
                item.value = item.label
                options_for_label.value.push(item)
            })
            //    console.log("options_for_label",options_for_label.value);
        })
    } catch (error) {
        console.error('获取标签失败:', error);

    }
    try {
        const response = await getQuestionsSingleScore(acs_id);
        // const singleScores = response.data.msg;
        // 将单题分数赋值给对应题型
        questionTypesForSingle.value = response.data.msg
        // console.log("questionTypesForSingle.value", questionTypesForSingle.value);
    } catch (error) {
        console.error('获取单题分数失败:', error);
    }
}
const questionTypes = reactive([]);
const dialogVisible = ref(false);
const dialogVisible_ForScore = ref(false);
const questionTypesForSingle = ref({});
const tableData = reactive([]);
const currentPaper = ref('A');
const options_for_label = ref([])
const modifyQuestionSingleScore = async () => {
    // console.log("questionTypesForSingle", questionTypesForSingle.value);
    try {
        await updateQuestionsSingleScore(acs_id, questionTypesForSingle.value.oneChoiceQuestions, questionTypesForSingle.value.multipleChoiceQuestions, questionTypesForSingle.value.fillBlankQuestions, questionTypesForSingle.value.judgeQuestions)
        uploadData()
    } catch (error) {
        console.log("hehrere");
        console.log("错误", error);
    }
    dialogVisible_ForScore.value = false
}

const totalScore = computed(() => {
    if (tableData.length === 0) {
        // console.log("你好邝智颖");
        return 0
    } else {
        tableData.forEach(item => {
            if (item.questionType === '单项选择题') {
                item.score = item.questionNum * questionTypesForSingle.value.oneChoiceQuestions
            }
            if (item.questionType === '多项选择题') {
                item.score = item.questionNum * questionTypesForSingle.value.multipleChoiceQuestions
            }
            if (item.questionType === '填空题') {
                item.score = item.questionNum * questionTypesForSingle.value.fillBlankQuestions
            }
            if (item.questionType === '判断题') {
                item.score = item.questionNum * questionTypesForSingle.value.judgeQuestions
            }
        });
        return tableData.reduce((total, item) => {
            // console.log("total,item.score", total, item);
            return total + item.score
        }, 0);
    }

});
onMounted(() => {
    fetchData();
});
import { useRoute, useRouter } from 'vue-router';
const router = useRouter();
const makePaper = () => {
    router.push({
        name: "paperList",
        // params: {
        //     subId,
        //     paperId: row.id,
        // }
    });
}
const openDialog = () => {
    dialogVisible.value = true;
}
const openDialogForScore = () => {
    dialogVisible_ForScore.value = true;
}
const updateDialogVisible = (value) => {
    dialogVisible.value = value;
}

const route = useRoute();
const subId = parseInt(route.params.subId);
// const postLoading = ref(true)
const testData = [
    {
        id: 40,
        questionType: "单项选择题",
        questionNum: 5,
        score: 23,
        t_user_and_a_c_s_id: 1,
        paperInfoId: null,
        subid: 1,
        paperType: "A",
        targetId: 2,
        createdAt: "2024-03-20T05:07:48.000Z",
        updatedAt: "2024-05-14T12:45:29.000Z",
        target_desc: [
            "数据结构+算法=程序",
            "线性表及其逻辑结构",
            "线性表的顺序存储结构—顺序表",
            "线性表的链式存储结构—单链表"
        ],
        label: [
            {
                id: 8,
                label: {
                    label: "链表"
                }
            },
            {
                id: 9,
                label: {
                    label: "栈"
                }
            },
            {
                id: 10,
                label: {
                    label: "队列"
                }
            },
            {
                id: 11,
                label: {
                    label: "二叉树"
                }
            }
        ],
        target_name: "课程目标1"
    },
    {
        id: 41,
        questionType: "填空题",
        questionNum: 5,
        score: 15,
        t_user_and_a_c_s_id: 1,
        paperInfoId: null,
        subid: null,
        paperType: "A",
        targetId: 2,
        createdAt: "2024-03-20T05:07:49.000Z",
        updatedAt: "2024-05-14T12:45:29.000Z",
        target_desc: [
            "数据结构+算法=程序",
            "线性表及其逻辑结构",
            "线性表的顺序存储结构—顺序表",
            "线性表的链式存储结构—单链表"
        ],
        label: [
            {
                id: 8,
                label: {
                    label: "链表"
                }
            },
            {
                id: 9,
                label: {
                    label: "栈"
                }
            },
            {
                id: 10,
                label: {
                    label: "队列"
                }
            },
            {
                id: 11,
                label: {
                    label: "二叉树"
                }
            }
        ],
        target_name: "课程目标1"
    },
    {
        id: 42,
        questionType: "单项选择题",
        questionNum: 4,
        score: 4,
        t_user_and_a_c_s_id: 1,
        paperInfoId: null,
        subid: null,
        paperType: "A",
        targetId: 3,
        createdAt: "2024-03-20T05:10:44.000Z",
        updatedAt: "2024-05-14T12:45:29.000Z",
        target_desc: [
            "线性表的链式存储结构—双链表",
            "线性表的链式存储结构—循环链表",
            "线性表的应用",
            "有序表"
        ],
        label: [
            {
                id: 6,
                label: {
                    label: "基础知识"
                }
            },
            {
                id: 7,
                label: {
                    label: "队列"
                }
            },
            {
                id: 12,
                label: {
                    label: "图论"
                }
            },
            {
                id: 14,
                label: {
                    label: "基础知识"
                }
            }
        ],
        target_name: "课程目标2"
    },
    {
        id: 46,
        questionType: "判断题",
        questionNum: 2,
        score: 8,
        t_user_and_a_c_s_id: 1,
        paperInfoId: null,
        subid: null,
        paperType: "A",
        targetId: 4,
        createdAt: "2024-03-20T08:25:10.000Z",
        updatedAt: "2024-05-14T12:45:29.000Z",
        target_desc: [
            "栈的基本概念",
            "栈的顺序存储结构-顺序栈",
            "栈的链式存储结构-链栈",
            "栈的应用"
        ],
        label: [],
        target_name: "课程目标3"
    },
    {
        id: 155,
        questionType: "多项选择题",
        questionNum: 1,
        score: 2,
        t_user_and_a_c_s_id: 1,
        paperInfoId: null,
        subid: null,
        paperType: "A",
        targetId: 41,
        label: [],
        createdAt: "2024-03-28T05:28:43.000Z",
        updatedAt: "2024-05-14T12:45:29.000Z"
    },
    {
        id: 173,
        questionType: "单项选择题",
        questionNum: 1,
        score: 1,
        t_user_and_a_c_s_id: 1,
        paperInfoId: null,
        subid: null,
        paperType: "A",
        label: [],
        targetId: 41,
        createdAt: "2024-05-14T12:44:53.000Z",
        updatedAt: "2024-05-14T12:45:29.000Z"
    }
]


const fetchData = async () => {
    try {
        getQuestionsTypeForSelection_func(acs_id)
        const response = await getTotalTarget(currentPaper.value, subId, acs_id);
        // console.log("response.data.content", response.data.code);
        // const rawData = response.data.content;
        const rawData = testData
        if (response.data.code === 500) return
        // 清空当前数据
        tableData.length = 0
        // tableData.splice(0);
        // 对原始数据进行处理
        const targetMap = new Map();
        // 课程目标和dataRows是一对多的关系
        // console.log("rawData", rawData);
        rawData.forEach(item => {
            if (!targetMap.has(item.target_name)) {
                targetMap.set(item.target_name, {
                    ...item,
                    target_desc: Array.isArray(item.target_desc) ? item.target_desc : [item.target_desc],
                    label: Array.isArray(item.label) ? item.label : [item.label],
                    dataRows: []
                });
            }
            targetMap.get(item.target_name).dataRows.push({
                ...item,
                questionType: item.questionType || '',
                questionNum: item.questionNum || 1,
                score: item.score || 0,
            });
        });

        // 把处理后的数据转换为数组并分配给tableData
        // targetMap.forEach((value, key) => {
        //     const groupData = value.dataRows.map((row, index) => ({
        //         ...row,
        //         target_name: key,
        //         isFirstOfGroup: index === 0,
        //         target_desc: value.target_desc,
        //         label: value.label,
        //         _isInserted: false,
        //     }));
        //     tableData.push(...groupData);
        // });
        targetMap.forEach((value, key) => {
            const groupData = [];
            for (let index = 0; index < value.dataRows.length; index++) {
                const row = value.dataRows[index];
                value.label = value.label.map(obj => {
                    const labelValue = obj.label.label;
                    return {
                        id: obj.id,
                        value: labelValue,
                        label: labelValue,
                    };
                });
                const rowData = {
                    ...row,
                    target_name: key,
                    isFirstOfGroup: index === 0,
                    target_desc: value.target_desc,
                    label: value.label,
                    _isInserted: false,
                };
                // console.log("value.label", value.label);
                rowData.index = index + 1;
                groupData.push(rowData);
            }
            tableData.push(...groupData);
        });
        originalTableData = JSON.parse(JSON.stringify(tableData));
    } catch (error) {
        console.log("123");
        ElMessage.error(error.message || '获取数据失败');
    }
};
const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
    if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
        if (row.isFirstOfGroup) {
            const rowCount = tableData.filter(item => item.target_name === row.target_name).length;
            return { rowspan: rowCount, colspan: 1 };
        }
        return { rowspan: 0, colspan: 0 };
    }
};
const addRow = async (objective) => {
    // console.log("objective", objective);
    // 找到该组的最后一行
    const lastIndex = tableData.reduce((lastIndex, current, index) => {
        return current.target_name === objective.target_name ? index : lastIndex;
    }, -1);

    // 获取目标分组的考核内容
    const targetDesc = tableData.find(item => item.target_name === objective.target_name)?.target_desc || [];

    const newRow = {
        ...objective,
        _isInserted: true,
        questionType: '单项选择题',
        questionNum: 1,
        score: 0,
        isFirstOfGroup: false,
        target_desc: targetDesc, // 为新行添加考核内容
    };

    const targetId = objective.targetId; // 取得当前目标的targetId
    const paperType = currentPaper.value; // 当前选中的卷类型
    const subId = objective.subid; // 取得当前目标的subId
    await addSingleTargetInfo({
        targetId,
        paperType,
        ACSId: acs_id
    })
    tableData.splice(lastIndex + 1, 0, newRow); // 在该组的最后一行后面插入新行
    // fetchData();
};
const deleteRow = async (rowToDelete) => {
    ElMessageBox.confirm("确定删除该题型吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const indexes = tableData
            .map((row, index) => (row.target_name === rowToDelete.target_name ? index : -1))
            .filter(index => index !== -1);

        if (indexes.length > 1) {
            const indexToDelete = tableData.indexOf(rowToDelete);
            // 如果删除的是第一行，则更新下一行为第一行
            if (tableData[indexToDelete].isFirstOfGroup) {
                // 保证不是最后一行，然后设置下一行为组的第一行
                if (indexToDelete < tableData.length - 1) {
                    tableData[indexToDelete + 1].isFirstOfGroup = true;
                }
            }
            try {
                await delSingleTargetInfo(rowToDelete.id);
                ElMessage.success("题型删除成功");
                fetchData();
            } catch (error) {
                ElMessage.error('题型删除失败: ' + error.message);
                return; // 如果删除失败，不从本地数据中删除该行
            }
            // await delSingleTargetInfo()
            tableData.splice(indexToDelete, 1);
        } else {
            ElMessage.warning('一个课程目标至少需要保留一种题型');
        }
    });

};


const uploadData = async () => {
    // if (totalScore.value !== 100) {
    //     ElMessage.error('总分必须等于100');
    //     return;
    // }
    for (const item of tableData) {
        if (item.score === 0) {
            ElMessage.error(`${item.target_name}下的题型 "${item.questionType}" 分数不能为0`);
            return; // 阻止保存操作
        }
    }
    // 检查是否存在相同题型的情况
    const typeMap = new Map();
    for (const item of tableData) {
        const key = `${item.target_name}-${item.questionType}`;
        if (typeMap.has(key)) {
            ElMessage.error(`${item.target_name}下存在相同题型: "${item.questionType}"`);
            return;
        }
        typeMap.set(key, true);
    }
    try {
        const uploadData = tableData.filter(item => !item._isInserted).map(item => ({
            id: item.id,
            target_name: item.target_name,
            target_desc: item.target_desc,
            // label:item.label,
            questionType: item.questionType,
            questionNum: item.questionNum,
            score: item.score
        }));
        console.log("上传的数据", {
            paperType: currentPaper.value,
            data: uploadData,
            subId
        });
        await updateTotalTarget({
            paperType: currentPaper.value,
            data: uploadData,
            subId
        })
        ElMessage.success('保存成功');

        fetchData();

    } catch (error) {
        ElMessage.error(error.message || '保存失败');
    }
};
</script>

<style scoped>
.outer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.upload-area {
    display: flex;
    margin: 10px;
    align-items: center;
    justify-content: space-between;
}

.target_desc_class::after {
    content: "";
    display: block;
    width: 80px;
    height: 1px;
    background: linear-gradient(244deg, rgba(255, 255, 255, 0) 0%, rgb(134, 198, 231) 50%);
}

.add-button {
    margin-left: 10px;
    color: #409EFF;
}

.delete-button {
    color: red;
}

.button {
    padding: 15px 30px;
    background-color: #409eff;
    color: white;
    border: none;
    border-radius: 5px;
    font-size: 20px;
    cursor: pointer;
    transition: background-color 0.3s;
    width: 100%;
    /* max-width: 1000px;  */
    box-sizing: border-box;
}
.chartsGroup {
    margin-top: 25px;

    .chartsStyle {
        display: flex;
        justify-content: space-around
    }
}
</style>
